package com.cee.sch.job.service.impl;

import com.cee.sch.job.dao.ScheduleJobLogMapper;
import com.cee.sch.job.dto.ScheduleJobDTO;
import com.cee.sch.job.dto.ScheduleJobLogDTO;
import com.cee.sch.job.model.ScheduleJob;
import com.cee.sch.job.service.ScheduleJobLogService;
import com.cee.sch.job.service.ScheduleJobService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Transactional
@Service
public class ScheduleJobLogServiceImpl implements ScheduleJobLogService {

    @Autowired
    private ScheduleJobLogMapper scheduleJobLogMapper;

    @Autowired
    private ScheduleJobService scheduleJobService;

    @Override
    public PageInfo<ScheduleJobLogDTO> getScheduleJobLogPageInfo(ScheduleJobLogDTO query) {
        Page<ScheduleJobLogDTO> startPage = PageHelper.startPage(query.getPagination().getPageNum(), query.getPagination().getPageSize());
        scheduleJobLogMapper.getList(query);
        return new PageInfo<ScheduleJobLogDTO>(startPage);
    }

    @Override
    public ScheduleJobLogDTO addScheduleJobLog(String jobName, String jobGroupName, ScheduleJobLogDTO scheduleJobLog) throws SchedulerException {
        ScheduleJobDTO scheduleJobDTO = scheduleJobService.getScheduleJobByNameAndGroup(jobName, jobGroupName);

        scheduleJobLog.setVisSysSchJobKey(scheduleJobDTO.getVisSysSchJobKey());
        scheduleJobLog.setJobName(scheduleJobDTO.getJobName());
        scheduleJobLog.setStartTime(new Date());
        scheduleJobLogMapper.insert(scheduleJobLog);

        return scheduleJobLog;
    }

    @Override
    public ScheduleJobLogDTO addScheduleJobLog(ScheduleJobLogDTO scheduleJobLog) {
        if (StringUtils.isEmpty(scheduleJobLog.getJobName()) && scheduleJobLog.getVisSysSchJobKey() == null) {
            throw new IllegalArgumentException("jobName or job ID could not be null!");
        }

        if (StringUtils.isEmpty(scheduleJobLog.getJobName())) {
            ScheduleJob scheduleJob = scheduleJobService.getScheduleJobById(scheduleJobLog.getVisSysSchJobKey());
            scheduleJobLog.setJobName(scheduleJob.getJobName());
        }
        scheduleJobLogMapper.insert(scheduleJobLog);;

        return scheduleJobLog;
    }

    @Override
    public void updateScheduleJobLog(ScheduleJobLogDTO jobLog) {
        scheduleJobLogMapper.updateById(jobLog);
    }
}
